﻿using System.Collections.Generic;
using System.Data;
using QD.Entity;
using QD.Data;
using QD.Data.Parameter;
using QD.DataBase.DBHelper;
using QD.Data.Page;

namespace QD.Repository
{
    public abstract class RepositoryMsSql<T> : RepositorySql<T> where T : DbEntity, IDbEntity<T>, new()
    {
        public RepositoryMsSql()
        {
            ParamBuilder = new MsSqlParamBuilder();
            DBHelper = MSSQLHelper.Instance;
            this.QuoteLeft = '[';
            this.QuoteRight = ']';
            this.ParamPrev = "@";
        }
        protected override void Init()
        {
            base.Init();
            PageListSQL = "uSP_Find_PageList";
            CountType = CommandType.Text;
            if (dtContext.PrimaryKey.AutoInCrement)
                InsertCommand += "SET " + ParamPrev + dtContext.PrimaryKey.Name + "=@@Identity;";
        }



        public override PageList<U> Find<U>(int currentpage, int pagesize, string where, string order)
        {
            IList<U> list = null;
            int total = 0;
            IDbDataParameter[] parameters = {
                         ParamBuilder.Create("@TableNames",dtContext.Name),
                         ParamBuilder.Create("@PrimaryKey",dtContext.PrimaryKey.Name),
                         ParamBuilder.Create("@Fields","*"),
                         ParamBuilder.Create("@PageSize",pagesize),
                         ParamBuilder.Create("@CurrentPage",currentpage>0?currentpage:1),
                         ParamBuilder.Create("@Filter",where),
                         ParamBuilder.Create("@Group",""),
                         ParamBuilder.Create("@Order",order),
                         ParamBuilder.Create("@RecordCount",0, ParameterDirection.Output),
                     };

            list = FindEntitys<U>(ConnectionString, CommandType.StoredProcedure, PageListSQL, parameters);

            total = (int)parameters[8].Value;

            PageList<U> records = new PageList<U>(list, total);

            return records;
        }

    }


}
